package net.lz1998.pbbot.plugin;

import lombok.RequiredArgsConstructor;
import net.lz1998.pbbot.bot.Bot;
import net.lz1998.pbbot.bot.BotPlugin;
import net.lz1998.pbbot.constant.BannedConstant;
import net.lz1998.pbbot.constant.GroupInfoConstant;
import net.lz1998.pbbot.constant.TitleConstant;
import net.lz1998.pbbot.mapper.PicsMapper;
import net.lz1998.pbbot.pojo.Pics;
import net.lz1998.pbbot.utils.Msg;
import onebot.OnebotApi;
import onebot.OnebotBase;
import onebot.OnebotEvent;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 设置专属头衔
 */
@Component
@RequiredArgsConstructor
public class GroupSpecialTitlePlugin extends BotPlugin {

    private final PicsMapper picsMapper;
    Map<Long,LocalDateTime> map = new HashMap<>();

    @Override
    public int onGroupMessage(@NotNull Bot bot, @NotNull OnebotEvent.GroupMessageEvent event) {
        String msg=event.getRawMessage().trim() ;
        long groupId = event.getGroupId();
        String[] arr = msg.split(" ");
	/*	if("存一下".equals(msg)) {
			findByMp3sList();
		}*/
        //图片
        if((TitleConstant.GROUPID==groupId||
                BannedConstant.GROUPID1==groupId||
                BannedConstant.GROUPID3==groupId)&&
                arr[0].equals(TitleConstant.TUPIAN)) {
            long userId = event.getUserId();
            Integer id=null;
            List<Pics> pics = null;
            if (arr.length == 1) {
                pics = picsMapper.findByPics(1, null);
            }
            if (arr.length == 2) {
                try {
                    id = Integer.parseInt(arr[1]);
                } catch (Exception e) {
                    bot.sendGroupMsg(groupId, Msg.builder().at(userId).text(GroupInfoConstant.INFO), false);
                    return MESSAGE_IGNORE;
                }
                pics = picsMapper.findByPics(1, id);
            }
            if (CollectionUtils.isEmpty(pics)) {
                pics = picsMapper.findByPics(1, null);
                int price = new Random().nextInt(3000 - 200 + 1) + 200;
                Msg info = Msg.builder().at(userId)
                        .text("\n\n")
                        .text(GroupInfoConstant.NOMEIZI)
                        .text("\n\n")
                        .text("今日妹子推荐,只需"+price+"块就能包夜哦,优惠多多!")
                        .text("\n\n")
                        .text("编号\t\t\t"+pics.get(0).getId())
                        .text("\n")
                        .text("姓名\t\t\t"+pics.get(0).getTitle())
                        .image(pics.get(0).getImgUrl().replaceAll("\\\\", "/"));
                bot.sendGroupMsg(groupId, info, true);
            } else {
                Msg info = null;
                int price = new Random().nextInt(3000 - 200 + 1) + 200;
                if (pics.size() == 1) {
                    info = Msg.builder()
                            .at(userId)
                            .text("\n\n")
                            .text("客官您点的妹子来了,童叟无欺,只需"+price+"块就能包夜哦!")
                            .text("\n\n")
                            .text("编号\t\t\t"+pics.get(0).getId())
                            .text("\n")
                            .text("姓名\t\t\t"+pics.get(0).getTitle())
                            .image(pics.get(0).getImgUrl().replaceAll("\\\\", "/"));
                }else{
                    info = Msg.builder()
                            .at(userId)
                            .text("\n\n");
                    if (Objects.isNull(id)) {
                        info.text("客官您点的妹子来了,童叟无欺,只需"+price+"块就能双飞哦!");
                    }else{
                        info.text("客官您点的妹子来了,童叟无欺,只需"+price+"块就能包夜哦!");
                    }
                    info.text("\n\n")
                            .text("编号\t\t\t"+String.valueOf(id==null?pics.get(0).getId():id))
                            .text("\n")
                            .text("姓名\t\t\t"+pics.get(0).getTitle())
                            .image(pics.get(0).getImgUrl().replaceAll("\\\\", "/"))
                            .text("\n\n");
                    if (Objects.isNull(id)) {
                        info.text("编号\t\t\t"+pics.get(1).getId());
                        info.text("\n");
                        info.text("姓名\t\t\t"+pics.get(1).getTitle());
                    }
                    info.image(pics.get(1).getImgUrl().replaceAll("\\\\", "/"));
                }
                if (map.get(userId) != null) {
                    long between = ChronoUnit.SECONDS.between(map.get(userId), LocalDateTime.now());
                    System.out.println(between);
                    if (between <= 30) {
                        //限制30s一次
                        bot.sendGroupMsg(groupId, Msg.builder().at(userId).text(TitleConstant.TISHI), true);
                    } else {
                        map.remove(userId);
                        bot.sendGroupMsg(groupId, info, false);
                    }
                } else {
                    if (TitleConstant.ADMINID != userId&&TitleConstant.ADMINID1 != userId) {
                        map.put(userId, LocalDateTime.now());
                    }
                    bot.sendGroupMsg(groupId, info, false);
                }
            }
        }
        //图片列表
        if((TitleConstant.GROUPID==groupId||
                BannedConstant.GROUPID1==groupId||
                BannedConstant.GROUPID3==groupId)&&msg.equals(TitleConstant.LIST)&&arr.length==1){
            long userId = event.getUserId();
            List<Pics> list = picsMapper.findByPicsList(1);
            StringBuilder sb = new StringBuilder();
            sb.append("\n");
            sb.append("随机100位");
            sb.append("\n");
            sb.append("编号 \t\t\t\t\t\t\t\t\t 姓名");
            sb.append("\n");
            for (int i = 0; i < list.size(); i++) {
                sb.append(list.get(i).getId()+"\t\t\t\t\t\t"+list.get(i).getTitle());
                sb.append("\n");
            }
            Msg info = Msg.builder()
                    .at(userId)
                    .text(sb.toString());
            bot.sendGroupMsg(groupId, info, false);
        }
        //(⊙o⊙)…
        if(TitleConstant.GROUPID==groupId&&msg.equals(TitleConstant.KAICHE)&&arr.length==1){
            long userId = event.getUserId();
			/*OnebotApi.GetGroupMemberInfoResp memberInfo = bot.getGroupMemberInfo(groupId, userId, true);
			if(memberInfo.getRole().equals("admin")||memberInfo.getRole().equals("owner")){*/
            List<Pics> pics = picsMapper.findByPics(0, null);
            Msg image = Msg.builder()
                    .at(userId)
                    .text("\n\n")
                    .text(pics.get(0).getTitle())
                    .text("\n\n")
                    .image(pics.get(0).getImgUrl().replaceAll("\\\\", "/"));
            bot.sendGroupMsg(groupId, image, true);
			/*}else{
				Msg info = Msg.builder()
						.at(userId)
						.text("您不是老司机,请勿强行开车..嘿嘿嘿");
				bot.sendGroupMsg(groupId, info, true);
			}*/
        }

        //小说列表
        if((TitleConstant.GROUPID==groupId||
                BannedConstant.GROUPID1==groupId||
                BannedConstant.GROUPID3==groupId)&&msg.equals(TitleConstant.XIAOSHUO)&&arr.length==1){
            long userId = event.getUserId();
            List<Pics> list = picsMapper.findByPicsList(3);
            StringBuilder sb = new StringBuilder();
            sb.append("\n");
            sb.append("随机100部");
            sb.append("\n");
            sb.append("编号 \t\t\t\t\t\t\t\t\t 标题");
            sb.append("\n");
            for (int i = 0; i < list.size(); i++) {
                sb.append(list.get(i).getId()+"\t\t\t\t\t\t"+list.get(i).getTitle());
                sb.append("\n");
            }
            Msg info = Msg.builder()
                    .at(userId)
                    .text(sb.toString());
            bot.sendGroupMsg(groupId, info, false);
        }

        //语音小说
        if(TitleConstant.GROUPID==groupId&&arr[0].equals(TitleConstant.YUYIN)){
            long userId = event.getUserId();
            Integer id=null;
            List<Pics> pics = null;
            if (arr.length == 1) {
                pics = picsMapper.findByPics(3, null);
            }
            if (arr.length == 2) {
                try {
                    id = Integer.parseInt(arr[1]);
                } catch (Exception e) {
                    bot.sendGroupMsg(groupId, Msg.builder().at(userId).text(GroupInfoConstant.INFO), false);
                    return MESSAGE_IGNORE;
                }
                pics = picsMapper.findByPics(3, id);
            }

            if (CollectionUtils.isEmpty(pics)) {
                pics = picsMapper.findByPics(3, null);
                Msg info = Msg.builder().at(userId)
                        .text("\n\n")
                        .text(GroupInfoConstant.NOXIAOSHUO)
                        .text("\n\n")
                        .text("今日小说推荐!")
                        .text("\n")
                        .text(pics.get(0).getTitle());
                bot.sendGroupMsg(groupId, info, true);
                bot.sendGroupMsg(TitleConstant.GROUPID, Msg.builder().record(pics.get(0).getImgUrl().replaceAll("\\\\", "/")), true);
            } else {
                Msg info = Msg.builder()
                        .at(userId)
                        .text("\n\n")
                        .text("客官您点的小说来了!")
                        .text("\n")
                        .text(pics.get(0).getTitle());
                if (map.get(userId) != null) {
                    long between = ChronoUnit.SECONDS.between(map.get(userId), LocalDateTime.now());
                    System.out.println(between);
                    if (between <= 60*2) {
                        //限制2分钟一次
                        bot.sendGroupMsg(groupId, Msg.builder().at(userId).text(TitleConstant.TISHI), true);
                    } else {
                        map.remove(userId);
                        bot.sendGroupMsg(groupId, info, false);
                        bot.sendGroupMsg(TitleConstant.GROUPID, Msg.builder().record(pics.get(0).getImgUrl().replaceAll("\\\\", "/")), true);
                    }
                } else {
                    if (TitleConstant.ADMINID != userId&&TitleConstant.ADMINID1 != userId) {
                        map.put(userId, LocalDateTime.now());
                    }
                    bot.sendGroupMsg(groupId, info, false);
                    bot.sendGroupMsg(TitleConstant.GROUPID, Msg.builder().record(pics.get(0).getImgUrl().replaceAll("\\\\", "/")), true);
                }
            }
        }

        if(TitleConstant.GROUPID==groupId&&msg.equals(BannedConstant.LKAICHE)&&arr.length==1){
            long userId = event.getUserId();
            OnebotApi.GetGroupMemberInfoResp memberInfo = bot.getGroupMemberInfo(groupId, userId, true);
            if(memberInfo.getRole().equals("admin")||memberInfo.getRole().equals("owner")){
                Pics pics = picsMapper.findByPics(2, null).get(0);
                List<OnebotBase.Message> video = Msg.builder()
                        .getMessageChain();
                video.add(OnebotBase.Message.newBuilder().setType("video")
                        .putData("cover", "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png")
                        .putData("url", pics.getImgUrl()).build());

                if (map.get(userId) != null) {
                    long between = ChronoUnit.SECONDS.between(map.get(userId), LocalDateTime.now());
                    System.out.println(between);
                    if (between <= 30) {
                        //限制30s一次
                        bot.sendGroupMsg(groupId, Msg.builder().at(userId).text(TitleConstant.TISHI), true);
                    } else {
                        map.remove(userId);
                        bot.sendGroupMsg(groupId, video, false);
                    }
                } else {
                    if (TitleConstant.ADMINID != userId&&TitleConstant.ADMINID1 != userId) {
                        map.put(userId, LocalDateTime.now());
                    }
                    bot.sendGroupMsg(groupId, video, false);
                }
            }else{
                Msg info = Msg.builder()
                        .at(userId)
                        .text("您不是老司机,请勿强行开车..嘿嘿嘿");
                bot.sendGroupMsg(groupId, info, true);
            }
        }
        //头衔
        if(TitleConstant.GROUPID==groupId&&msg.startsWith(TitleConstant.HEARD)&&arr.length>1){
            if(arr.length==2) {
                if (arr[1].startsWith(TitleConstant.ADMINHEARD)&&event.getUserId()!=TitleConstant.ADMINID) {
                    bot.setGroupSpecialTitle(groupId, event.getUserId(), TitleConstant.OTHERHEARD, 1);
                } else {
                    bot.setGroupSpecialTitle(groupId, event.getUserId(), arr[1], 1);
                }
            }
            if(arr.length==4){
                try {
                    if(arr[2].startsWith("qq=")){
                        String[] idArr = arr[2].split("=");
                        Long user_id = Long.valueOf(idArr[1].substring(1, idArr[1].lastIndexOf('"')));
                        Long adminId = event.getUserId();
                        if(user_id==TitleConstant.ADMINID){
                            bot.setGroupSpecialTitle(groupId, adminId, TitleConstant.CURRENTHEARD, 1);
                        }else{
                            if(adminId!=TitleConstant.ADMINID&&arr[3].startsWith(TitleConstant.ADMINHEARD)){
                                bot.setGroupSpecialTitle(groupId, adminId, TitleConstant.OTHERHEARD, 1);
                            }else {
                                bot.setGroupSpecialTitle(groupId, user_id, arr[3], 1);
                            }
                        }
                    }else{
                        bot.setGroupSpecialTitle(groupId,event.getUserId(),TitleConstant.ZHUHEARD,1);
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        return MESSAGE_IGNORE;
    }

    /**
     * 拼接路径
     * @param path
     * @param list
     * @return
     */
    public static List<String> traverseFolder(String path,List<String> list) {
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();

            if (null == files || files.length == 0) {
                System.out.println("文件夹是空的!");
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        traverseFolder(file2.getAbsolutePath(),list);
                    }else{
                        list.add(file2.getAbsolutePath());
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
        return list;
    }

    public List<Pics> findByPicsList() {
        List<String> list = new ArrayList<>();
        list = traverseFolder("E://gif",list);
        Pics pics = new Pics();
        list.forEach(l->{
            System.out.println("http://47.93.130.192:8088/"+l.substring(l.indexOf("gif")).replaceAll("\\\\", "/"));
            System.out.println(l.substring(l.indexOf("gif") + 4, l.lastIndexOf("\\")));
            pics.setClicknum(0);
            pics.setImgUrl("http://47.93.130.192:8088/"+l.substring(l.indexOf("gif")).replaceAll("\\\\", "/"));
            pics.setFlag(0);
            pics.setCreateTime(new Date());
            pics.setUpdateTime(new Date());
            pics.setTitle(l.substring(l.indexOf("gif") + 4, l.lastIndexOf("\\")));
            picsMapper.insertSelective(pics);
            System.out.println("保存一组记录"+l+"成功");
        });
        return new ArrayList<>();
    }

    public List<Pics> findByMp3sList() {
        List<String> list = new ArrayList<>();
        list = traverseFolder("E://mp3s",list);
        Pics pics = new Pics();
        //  http://47.93.130.192:8088/mp3/QQ约会高中女生.amr
        list.forEach(l->{
            System.out.println("http://47.93.130.192:8088/"+l.substring(l.indexOf("mp3")).replaceAll("\\\\", "/"));
		/*	System.out.println(l.substring(l.indexOf("gif") + 4, l.lastIndexOf("\\")));
			pics.setClicknum(0);
			pics.setImgUrl("http://47.93.130.192:8088/"+l.substring(l.indexOf("mp3")).replaceAll("\\\\", "/"));
			pics.setFlag(0);
			pics.setCreateTime(new Date());
			pics.setUpdateTime(new Date());
			pics.setTitle(l.substring(l.indexOf("gif") + 4, l.lastIndexOf("\\")));*/
            //picsMapper.insertSelective(pics);
            System.out.println("保存一组记录"+l+"成功");
        });
        return new ArrayList<>();
    }
}
